package router

import (
	"fmt"
	"html/template"

	// "log"
	"strconv"

	repo "goWeb-blog/repo"
	"net/http"
	"regexp"

	"github.com/gorilla/sessions"
)

type Blog struct {
	U      repo.User
	Posts  []repo.Post
	IfLoad bool
	APost  repo.Post
}
type Home struct {
	U     repo.User
	Posts []repo.Post
}
type UpPost struct{
	User     repo.User
	Post repo.Post
}
var store = sessions.NewCookieStore([]byte("secret-key"))

func BasicRouter() {
	http.HandleFunc("/index", blogIndex)
	http.HandleFunc("/home", blogHome)
	http.HandleFunc("/home/", visitHome)
	http.HandleFunc("/post/", visitPost)
    http.HandleFunc("/delete/",delete)
	http.HandleFunc("/update/",update)
	http.HandleFunc("/up",up)
	http.HandleFunc("/addPost/",addPost)
	http.Handle("/css/", http.FileServer(http.Dir("wwwroot")))
	http.Handle("/img/", http.FileServer(http.Dir("wwwroot")))
	http.Handle("/js/", http.FileServer(http.Dir("wwwroot")))
}
func Ability() {
	http.HandleFunc("/login", login)
	http.HandleFunc("/signUp", signUp)
	http.HandleFunc("/dengChu", dengChu)
}
func up(w http.ResponseWriter, r *http.Request){
	pid,_:=strconv.Atoi(r.PostFormValue("pid"))
	var p = &repo.Post{
		Pid: pid,
		Title: r.PostFormValue("UpPostTitle"),
		Content:  r.PostFormValue("UpPostContent"),
	  }
	repo.UpDatePost(p)
	var b = YanZheng(r)
	x := fmt.Sprintf("/home/%d", b.U.Id)
	http.Redirect(w, r, x, http.StatusFound)
}
func update(w http.ResponseWriter, r *http.Request) {
	pattern, _ := regexp.Compile(`/update/(\d+)`)
	matches := pattern.FindStringSubmatch(r.URL.Path)
	if len(matches) > 0 {
		//这个是pid
		postID, _ := strconv.Atoi(matches[1])
        var p = repo.GetAPost(postID)
		//查找文章内容，放一起丢进去。
		var b = YanZheng(r)
	    var up = &UpPost{
			User: b.U,
			Post: p,
		}
		t, _ := template.ParseFiles("template/update.html")
		t.ExecuteTemplate(w, "content", up)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
func addPost(w http.ResponseWriter, r *http.Request) {
	pattern, _ := regexp.Compile(`/addPost/(\d+)`)
	matches := pattern.FindStringSubmatch(r.URL.Path)
	if len(matches) > 0 {
		//这个是uid
		userID, _ := strconv.Atoi(matches[1])
		//接下来我应该把文章内容啥的插入数据库
        var p = &repo.Post{
          Title: r.PostFormValue("PostTitle"),
		  Content:  r.PostFormValue("PostContent"),
		  User_id: userID,
		  Slug :"111",
		  Markdown :"hello" ,
		  Catrgoryid :"1",
		  ViewCount :0,
		  Type :0,
		  Author :repo.QueryUserNameByUID(userID),
		}
		repo.InsertPost(p)
		//返回
		var b = YanZheng(r)
		x := fmt.Sprintf("/home/%d", b.U.Id)
		http.Redirect(w, r, x, http.StatusFound)
	}else{
		w.WriteHeader(http.StatusNotFound)
	}
}
func dengChu(w http.ResponseWriter, r *http.Request) {
	session, err := store.Get(r, "session-id")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	session.Options.MaxAge = -1
	session.Save(r, w)
	http.Redirect(w, r, "/index", http.StatusFound)
}
func visitPost(w http.ResponseWriter, r *http.Request) {
	pattern, _ := regexp.Compile(`/post/(\d+)`)
	matches := pattern.FindStringSubmatch(r.URL.Path)
	t, _ := template.ParseFiles("template/post.html")
	if len(matches) > 0 {
		postID, _ := strconv.Atoi(matches[1])
		var x = YanZheng(r)
		x.APost = repo.GetAPost(postID)
		t.ExecuteTemplate(w, "content", x)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}


func delete(w http.ResponseWriter, r *http.Request) {
	pattern, _ := regexp.Compile(`/delete/(\d+)`)
	matches := pattern.FindStringSubmatch(r.URL.Path)
	if len(matches) > 0 {
		postID, _ := strconv.Atoi(matches[1])
		repo.DeletePost(postID)
		var b = YanZheng(r)
		x := fmt.Sprintf("/home/%d", b.U.Id)
		http.Redirect(w, r, x, http.StatusFound)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
func visitHome(w http.ResponseWriter, r *http.Request) {
	pattern, _ := regexp.Compile(`/home/(\d+)`)
	matches := pattern.FindStringSubmatch(r.URL.Path)
	t := template.New("home")
	t, _ = t.ParseFiles("template/home.html", "template/layout.html")
	a := make(map[string]interface{})
	var x = YanZheng(r)
	a["UserId"] = x.U.Id
	if len(matches) > 0 {
		homeID, _ := strconv.Atoi(matches[1])
		u, posts := repo.GoHome(homeID)
		a["HomeId"] = u.Id
		a["HomeName"] = u.UserName
		a["Posts"] = posts
		a["HasPost"] = true
		for _, p := range posts {
			if p.Pid == 0 {
				a["HasPost"] = false
				break
			}
		}
		if x.U.Id == u.Id {
			a["CanEdit"] = true
		} else {
			a["CanEdit"] = false
		}
		t.ExecuteTemplate(w, "layout", a)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
func signUp(w http.ResponseWriter, r *http.Request) {
	var u = repo.User{
		UserName: r.FormValue("Rusername"),
		Password: r.FormValue("Rps"),
		Email:    r.FormValue("Remail"),
	}
	n := repo.Register(u)
	// w.Write([]byte("<script>alert('账号或者密码不正确')</script>"))
	str := fmt.Sprintf("<script>alert('您的账号是 %v ,请牢记它，在登陆时会用')</script>", n)
	w.Write([]byte(str))
}

func login(w http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.FormValue("userid"))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	var u = repo.User{
		Id:       n,
		Password: r.FormValue("Lpassword"),
	}
	if x, u := repo.Login(u.Id, u.Password); x {
		session, _ := store.Get(r, "session-id") // 获取 session
		session.Options.MaxAge = 60
		session.Values["username"] = u.UserName // 将用户名存储到 session 中
		session.Values["Id"] = u.Id
		session.Values["isLoad"] = true
		session.Save(r, w)
		fmt.Println("已登录")
		http.Redirect(w, r, "/index", http.StatusFound)

	} else {
		http.Redirect(w, r, "/index", http.StatusFound)
	}

}
func YanZheng(r *http.Request) Blog {
	session, _ := store.Get(r, "session-id")
	_, ok := session.Values["username"]
	var b = Blog{
		IfLoad: false,
		U: repo.User{
			UserName: "游客",
			Id:       0,
		},
	}
	if ok {
		n, _ := strconv.Atoi(fmt.Sprintf("%v", session.Values["Id"]))
		b = Blog{
			U: repo.User{
				Id:       n,
				UserName: fmt.Sprintf("%v", session.Values["username"]),
			},
			IfLoad: true,
		}
	}
	return b
}
func blogIndex(w http.ResponseWriter, r *http.Request) {
	funcMap := template.FuncMap{"postList": repo.PostIndexList}
	t := template.New("index").Funcs(funcMap)
	t, err := t.ParseFiles("template/index.html", "template/layout.html")

	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
	}
	err = t.ExecuteTemplate(w, "layout", YanZheng(r))

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}

}
func blogHome(w http.ResponseWriter, r *http.Request) {
	t := template.New("home")

	t, err := t.ParseFiles("template/home.html", "template/layout.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
	}
	err = t.ExecuteTemplate(w, "layout", YanZheng(r))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
// func blogPost(w http.ResponseWriter, r *http.Request) {
// 	t := template.New("post")
// 	t, err := t.ParseFiles("template/post.html", "template/layout.html", "template/comment.html")
// 	if err != nil {
// 		w.WriteHeader(http.StatusInternalServerError)
// 		w.Write([]byte(err.Error()))
// 	}
// 	err = t.ExecuteTemplate(w, "layout", YanZheng(r))
// 	if err != nil {
// 		http.Error(w, err.Error(), http.StatusInternalServerError)
// 	}
// }
